import React, { useState, useEffect } from 'react';
import './WebSocketManager.css';

interface WebSocketManagerProps {
  onClose?: () => void;
}

const WebSocketManager: React.FC<WebSocketManagerProps> = ({ onClose }) => {
  const [port, setPort] = useState<string>('');
  const [isServerRunning, setIsServerRunning] = useState(false);
  const [currentPort, setCurrentPort] = useState<number | null>(null);

  useEffect(() => {
    // 监听WebSocket服务器状态
    window.ipcApi.onWsServerStarted((event, { port }) => {
      setIsServerRunning(true);
      setCurrentPort(port);
    });

    // 获取当前WebSocket服务器状态
    window.ipcApi.getWsServerStatus();

    return () => {
      window.ipcApi.removeAllListeners('ws-server-started');
    };
  }, []);

  const handleStartServer = () => {
    const portNumber = port ? parseInt(port, 10) : 0;
    if (port && (portNumber < 1024 || portNumber > 65535)) {
      alert('端口号必须在1024-65535之间');
      return;
    }
    window.ipcApi.startWsServer(portNumber);
  };

  const handleStopServer = () => {
    window.ipcApi.stopWsServer();
    setIsServerRunning(false);
    setCurrentPort(null);
  };

  return (
    <div className="websocket-manager">
      <div className="websocket-manager-header">
        <h3>WebSocket服务器设置</h3>
        {onClose && (
          <button className="close-button" onClick={onClose}>×</button>
        )}
      </div>
      <div className="websocket-manager-content">
        {isServerRunning ? (
          <div className="server-status">
            <div className="status-text">
              <span className="status-dot active"></span>
              服务器运行中 - 端口: {currentPort}
            </div>
            <button onClick={handleStopServer}>停止服务器</button>
          </div>
        ) : (
          <div className="server-controls">
            <div className="input-group">
              <label>端口号:</label>
              <input
                type="number"
                value={port}
                onChange={(e) => setPort(e.target.value)}
                placeholder="留空将自动分配端口"
                min="1024"
                max="65535"
              />
            </div>
            <button onClick={handleStartServer}>启动服务器</button>
          </div>
        )}
        <div className="connection-help">
          <h4>连接说明</h4>
          <ol>
            <li>在手机上打开 Auto.js</li>
            <li>点击右上角菜单</li>
            <li>选择"连接电脑"</li>
            <li>输入电脑IP地址和端口号</li>
            <li>点击"连接"</li>
          </ol>
        </div>
      </div>
    </div>
  );
};

export default WebSocketManager; 